#tools/polling.py

import threading
import time
from tools import config
import logging

logging.basicConfig (level = logging.DEBUG, format = "%(created)-15s %(msecs)d %(levelname)8s %(thread)d %(name)s %(message)s")
log = logging.getLogger (__name__)

class PollThread(threading.Thread) :
	""" """
	def __init__ (self, nodes_and_conns) :
		"""Initial stuff."""
		self.debug = config.getDebug ()
		if self.debug :
			log.debug ("__init__")
		threading.Thread.__init__ (self)
		self.nodes = nodes_and_conns
		self.sleeptime = config.getPollInterval()

	def run (self) :
		""" """
		idx=0
		while 1 :
			if self.debug :
				log.debug ("simple poll run")
			if self.nodes[1][idx].is_alive :
				for plugin in self.nodes[2][idx] :
					self.nodes[4][idx].acquire ()
					self.nodes[1][idx].send_msg ("get %s\r\n" % plugin, \
						self.nodes[0][idx])
#					self.nodes[1][idx].write_to = self.nodes[0][idx]
#					self.nodes[1][idx].ready_to_send = True
					while self.nodes[1][idx].ready_to_send :
						pass
					self.nodes[4][idx].notifyAll ()
					self.nodes[4][idx].release ()
			time.sleep (self.sleeptime / len (self.nodes[0]))
			idx += 1
			if idx == len (self.nodes[0]) :
				idx = 0

class BPollThread (threading.Thread) :
	""" """
	def __init__ (self, nodes_and_conns) :
		""" """
		self.debug = config.getDebug ()
		if self.debug :
			log.debug ("__init__")
		threading.Thread.__init__ (self)
		self.nodes = nodes_and_conns
		self.sleeptime = config.getBPollInterval ()
	
	def run (self) :
		""" """
		idx = 0
		while 1 :
			if self.debug :
				log.debug ("buff poll run")
			if self.nodes[1][idx].is_alive :
				for plugin in self.nodes[3][0][idx] :
					i = self.nodes[3][0][idx].index (plugin)
					seqn = self.nodes[3][1][idx][i]
					self.nodes[4][idx].acquire ()
					self.nodes[1][idx].send_msg ("get %s %s\r\n" % (plugin, \
						seqn), self.nodes[0][idx])
#					self.nodes[1][idx].write_to = self.nodes[0][idx]
#					self.nodes[1][idx].ready_to_send = True
					while self.nodes[1][idx].ready_to_send :
						pass
					self.nodes[4][idx].notifyAll ()
					self.nodes[4][idx].release ()
			time.sleep (self.sleeptime / len (self.nodes[0]))
			idx += 1
			if idx == len (self.nodes[0]) :
				idx = 0

